﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace ERPStore.ProductRating.Controllers
{
	// [HttpControllerConfiguration(ActionValueBinder = typeof(System.Web.Http.ModelBinding.HttpRequestParameterBinding))]
	public class RatingApiController : ApiController
	{
		public RatingApiController()
		{

		}

		[HttpGet]
		public DateTime Ping()
		{
			return DateTime.Now;
		}

		public Models.ProductRate GetProductRate(string id)
		{
			var fileName = string.Format("{0}\\app_data\\productrating\\{1}.xml", GlobalConfiguration.Configuration.Settings.PhysicalPath.TrimEnd('\\'), id);
			Models.ProductRate pr = null;

			if (System.IO.File.Exists(fileName))
			{
				var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Models.ProductRate));
				using (var reader = System.IO.File.OpenRead(fileName))
				{
					pr = serializer.ReadObject(reader) as Models.ProductRate;
				}
			}
			else
			{
				pr = new Models.ProductRate();
			}

			return pr;
		}

		[System.Web.Http.HttpPost]
		[System.Web.Http.HttpPut]
		public Models.ProductRate RateProductByCode(Models.Rate rate)
		{
			if (rate == null
				|| rate.ProductCode == null
				|| rate.Level == 0)
			{
				return new Models.ProductRate();
			}
			var fileName = string.Format("{0}\\app_data\\productrating\\{1}.xml", GlobalConfiguration.Configuration.Settings.PhysicalPath.TrimEnd('\\'), rate.ProductCode);
			Models.ProductRate pr = null;

			var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Models.ProductRate));
			if (System.IO.File.Exists(fileName))
			{
				using(var reader = System.IO.File.OpenRead(fileName))
				{
					pr = serializer.ReadObject(reader) as Models.ProductRate;
				}
			}
			else
			{
				pr = new Models.ProductRate();
			}

			switch (rate.Level)
			{
				case 1 :
					pr.Level1Count++;
					break;
				case 2 :
					pr.Level2Count++;
					break;
				case 3 :
					pr.Level3Count++;
					break;
				case 4 :
					pr.Level4Count++;
					break;
				case 5 :
					pr.Level5Count++;
					break;
				default:
					break;
			}
			using (var writer = System.IO.File.OpenWrite(fileName))
			{
				serializer.WriteObject(writer, pr) ;
			}

			return pr;
		}


	}
}
